/**
 * 通用方法
 */

/**
 * 通用方法
 */
import {
  MessageBox,
  Message
} from 'element-ui'

// save or restore
export function saveAndRestore(store, key, value) {
  if (value === undefined) {
    return JSON.parse(store.getItem(key));
  } else {
    store.setItem(key, JSON.stringify(value));
  }
}

// 存取local 
export function localSave(key, value) {
  return saveAndRestore(top.localStorage, key, value) || saveAndRestore(top.localStorage, key, value);
}

// 存取session
export function sessionSave(key, value) {
  return saveAndRestore(top.sessionStorage, key, value) || saveAndRestore(sessionStorage, key, value);
}

// 获取日期
export function getFullDate(date,split){
  var _s = split || '/';
  if(date instanceof Date){
    return `${date.getMonth() + 1}${_s}${date.getDate()}`;
  }
}

// 获取日期范围内的所有日期
export function getRangeDate(start,end){
  let day = 1000 * 60 * 60 * 24;
  let _start = start.getTime();
  let _end = end.getTime();
  let res = [];
  while(_start <= _end){
    res.push(new Date(_start));
    _start += day;
  }
  return res;
}

// 拿token
export function getToken() {
  let userinfo = localSave('userInfo');
  return localSave("token") || (userinfo ? userinfo.token : null);
}

// set 转 list
export function setToArr(set) {
  let res = [];
  for (let item of set.values()) {
    res.push(item);
  }
  return res;
}

// 清除元素
export function clearObj(obj, val) {
  let _val = val !== undefined ? val : '';
  for (let k in obj) {
    obj[k] = _val;
  }
}

// 更新元素 
export function updateObjBy(target, ref) {
  for (let k in target) {
    if (ref[k] !== undefined && target[k] !== undefined) {
      target[k] = ref[k];
    }
  }
}

// 递归修改对象名称
export function objRename(obj, childeKey, oldName, newName) {
  if (obj instanceof Array) {
    for (var i = 0; i < obj.length; i++) {
      objRename(obj[i]);
    }
  } else if (obj && obj[oldName]) {
    obj[newName] = obj[oldName]
    childeKey && objRename(obj[childeKey]);
    delete obj[oldName]
  }
}

// 递归树形数据，可对每个节点进行处理处理
export function recusiveDispose(data, childrenKey, dispose, level, index) {
  var l = typeof level === 'number' ? level : 1;
  var i = typeof index === 'number' ? index : 0;
  var children = data[childrenKey];
  if (children instanceof Array) {
    for (var j = 0, len = children.length; j < len; j++) {
      recusiveDispose(children[j], childrenKey, dispose, l + 1, i + 1);
    }
  }
  dispose(data, l, i);
}

// 对比key处理树数据某个节点下的所有节点
export function nodeRecusiveDispose(data, node, key, childrenKey, dispose, isDis) {
  var children = data[childrenKey];
  // 匹配处理的节点
  var _isDis = isDis;
  var isCur;

  if (data[key] === node[key]) {
    isCur = _isDis = true;
  }

  if (_isDis) {
    dispose(data);
  }

  if (children instanceof Array) {
    for (var j = 0, len = children.length; j < len; j++) {
      if (nodeRecusiveDispose(children[j], childrenKey, dispose, _isDis)) {
        return;
      }
    }
  }

  // 如果当前节点是匹配节点则不再查其他分支
  return isCur;
}

// 处理某分支所有数据
export function branchDispose(root, childrenKey, dispose) {
  var children = root[childrenKey];

  dispose(root);
  if (children instanceof Array) {
    for (var i = 0, len = children.length; i < len; i++) {
      branchDispose(children[i], childrenKey, dispose);
    }
  }
}

// 通过数组对象id 获取 idx
export function getIndex(list, id) {
  for (var i = 0; i < list.length; i++) {
    if (list[i].id === id) return i;
  }

  return -1;
}

// 通过数组对象 key 获取对象
export function getObj(list, key,keyVal) {
  for (var i = 0; i < list.length; i++) {
    let obj = list[i]
    if (obj[key] == keyVal) return obj;
  }
}

// 对象数组唯一存储 （可用于跨页勾选）
export function selectedList(list, item, status) {
  var id = item.id;
  var index = getIndex(list, id);
  if (status) {
    // 选中
    if (index === -1) list.push(item);
  } else {
    // 反选
    if (index !== -1) list.splice(index, 1);
  }
}

export function genMultiObj(obj, count) {
  let res = [];
  while (count-- > 0) {
    res.push(obj);
  }
  return res;
}


// 生成范围数组
export function genRangeList(start, end, unit) {
  let res = [];
  let u = unit || '';
  for (var i = start; i <= end; i++) {
    res.push(i + u);
  }
  return res;
}

// 将多个数组合并成对象
/**
 * 
 * @param {Array<String>} keyList 
 * @param {Array<Array>} arrList 
 */
export function arraysToObjList(keyList, arrList) {
  let res = [];
  // 拆分key
  keyList.forEach((key, i) => {
    // 拆分数组，组成对象
    arrList[i].forEach((item, idx) => {
      if (!res[idx]) {
        res.push({});
      }

      res[idx][key] = item
    })
  })
  return res;
}

// 生成月、日、周数据
export function genMonthDayWeekList() {
  let keys = ["label", "val"];

  let monthLabel = genRangeList(1, 12, '月');
  let monthVal = genRangeList(1, 12);
  let monthList = arraysToObjList(keys, [monthLabel, monthVal]);

  let dayLabel = genRangeList(1, 31, '日');
  let dayVal = genRangeList(1, 31);
  let dayList = arraysToObjList(keys, [dayLabel, dayVal]);

  let weekLabel = [
    "星期一",
    "星期二",
    "星期三",
    "星期四",
    "星期五",
    "星期六",
    "星期日"
  ];
  let weekVal = genRangeList(1, 7);
  let weekList = arraysToObjList(keys, [weekLabel, weekVal]);

  return {
    weekList,
    monthList,
    dayList
  }
}

// 将列表和选中的值进行拆分，形成多个list
/**
 * 
 * @param {Array<Object> | Array<String>} list 有序数组
 * @param {Array<String>} selList 
 * @param {String} key 
 */
export function splitListBySelected(list, selList, key) {
  let k = key || 'val';
  let res = [];

  // 将对应key 以数组形式取出来
  let _list = list.map(item => {
    return item[k] || item;
  })

  // 对选中的值做排序
  let _selList = selList.slice().sort(function (a, b) {
    try {
      return parseInt(a) - parseInt(b);
    } catch (e) {
      return a > b ? 1 : -1;
    }
  })

  for (let i = 0, len = _selList.length; i < len; i++) {
    let item = _selList[i];
    let idx = getIndex(item);

    // 非最后一个选中
    if (i < len - 1) {
      let nextIndex = getIndex(_selList[i + 1]);
      res.push(list.slice(idx, nextIndex));
    } else {
      res.push(list.slice(idx));
    }
  }
  return res;

  function getIndex(item) {
    let idx = _list.indexOf(item)
    if (idx === -1) throw Error(`list 中找不到相应的值 ${item}`);

    return idx;
  }
}

// 根据路由配置生成嵌入其他页面的路由
export function genEmbedRoute(route) {
  let children = route.children;
  let res = [];
  if (children) {
    let i = children.length;
    while (i--) {
      let r = children[i];
      // 递归 children
      if (r.children) {
        res = res.concat(genEmbedRoute(r));
      } else {
        res.push({
          name: `_${r.name}`,
          component: r.component,
          hiden: true,
          path: `/embed/${r.name}`
        })
      }
    }
  } else {
    res = [route];
  }

  return res;
}

// 对象参数转url参数
export function paramsToUrl(params) {
  var res = '';
  try {
    let p = typeof params === 'string' ? JSON.parse(params) : params;
    for (let k in p) {
      if (res) {
        res += '&';
      }
      res += `${k}=${p[k]}`;
    }
  } catch (err) {
    res = params;
  }

  return res;
}

// 获取自适应span
export function getAutoSpan(el) {
  let w = el.clientWidth;
  let span = 0;
  if (w > 1400) {
    span = 6;
  } else if (w > 1000) {
    span = 8;
  } else if (w > 600) {
    span = 12;
  } else {
    span = 24;
  }

  return span;
}

// 获取某对象的所有父节点
export function getTreeParents(root, child, childrenKey, res) {
  let curList = root[childrenKey];
  let idx;
  res = res || [root];

  if (root === child) {
    return res;

  } else if (curList && (idx = curList.indexOf(child)) > -1) {
    res.push(curList[idx]);
    return res;

  } else {
    // 判断是否有子节点
    if (curList instanceof Array) {
      for (var i = 0, len = curList.length; i < len; i++) {
        res.push(curList[i]);
        let _res = getTreeParents(curList[i], child, childrenKey, res);
        if (_res) {
          return _res;
        }
      }
    }

    res.splice(res.length - 1, 1);
  }
}


/**
 * element 方法
 */
// 增删改提示
export function tip(type, status) {
  var msg;
  var s = status === "success" ? "成功" : "失败";

  switch (type) {
    case "add": {
      msg = `添加${s}`;
      break;
    }
    case "edit": {
      msg = `修改${s}`;
      break;
    }
    case "del": {
      msg = `删除${s}`;
      break;
    }
    default: {
      msg = type;
    }
  }
  Message({
    message: msg,
    type: status
  });
}

// 调用form 表单校验 ， 可自定义提示
/**
 * 
 * @param {el-form} form el-form 对象
 * @param {Function} suc 成功的回调 , 可传msg
 * @param {String} msg 提示信息
 */
export function checkForm(form, suc, msg) {
  var defTip = '请按要求输入相应字段'
  var _msg = suc instanceof Function ? msg : suc;
  var res = null;
  form.validate(function (valid) {
    if (valid) {
      try {
        res = true;
        suc instanceof Function && suc();
      } catch (e) {
        tip('form 表单校验失败', 'error');
        console.error('form 表单校验失败', e);
      }
    } else {
      // 防止校验阻塞提交
      res = false;
      tip(_msg || defTip, 'warning');
    }
  })

  return res;
}

// 生成英文字母
function charFactor(isUplower) {
  var start = isUplower ? 65 : 97;
  return String.fromCharCode(parseInt(Math.random() * 26) + start);
}

// 生成单词（首字母大写）
function strFactor(min, max) {
  min = min || 5;
  max = max || 15;
  var num = min + parseInt(Math.random() * max);
  var result = "";
  for (var i = 0; i < num; i++) {
    if (i === 0) {
      result += charFactor(true);
    } else {
      result += charFactor();
    }
  }
  return result;
}

// 生成文章
function articleFactor(wordNum) {
  wordNum = wordNum || 100;
  var article = "";
  for (var i = 0; i < wordNum; i++) {
    article += strFactor() + "  ";
  }
  return {
    title: strFactor(),
    type: "system",
    article
  };
}

//时间戳转 201803032305 格式 或自定义年月的分隔符
function transCommDate(ts,s){
  var D , y,M,d,H,m,time;

  function format(n){
    if(n <10){
      return "0" + n;
    }
    return n;
  }
  s = s || "";
  D = new Date(ts);
  y = D.getFullYear();
  M = format(D.getMonth() + 1);
  d = format(D.getDate());
  H = format(D.getHours());
  m = format(D.getMinutes());
  time = y + s + M + s + d + s + H + s + m;
  return time;
}

//时间戳转中文时间
function transChineseDate(ts){
  var D,y,M,d,h,m,s,time;

  function format(n){
    if(n <10){
      return "0" + n;
    }
    return n;
  }

  D = new Date(ts);
  y = D.getFullYear() + "年";
  M = D.getMonth()  + 1 + "月";
  d = D.getDate() + "日 ";
  h = format(D.getHours()) + ":";
  m = format(D.getMinutes()) +":";
  s = format(D.getSeconds());
  time = y + M + d + h + m + s;
  return time;
}

//获取当前年月日
function getDateTime(){
  let d = new Date();

  function format(n){
    if(n <10){
      return "0" + n;
    }
    return n;
  }

  return d.getFullYear()  + '-' + format(d.getMonth() + 1) + '-' + d.getDate();
}
//剔除空值
function objFilter(obj){
  let newObj = {};
  for(let k in obj){
    let v = obj[k];
    if((typeof v === 'string' && v.trim() !=='') || (typeof v === 'number' && v >= 0) || (v instanceof Array && v.length >0)){
      newObj[k] = v;
    }
  }
  return newObj;
}

//随机颜色
function randomColor(){
  var colorStr="";
  //字符串的每一字符的范围
  var randomArr=['0','1','2','3','4','5','6','7','8','9','a','b','c','d','e','f'];
  //产生一个六位的字符串
  for(var i=0;i<6;i++){
    //15是范围上限，0是范围下限，两个函数保证产生出来的随机数是整数
    colorStr+=randomArr[Math.ceil(Math.random()*(15-0)+0)];
  }
  return "#"+colorStr;
}

//转换css key
function transCssKey(key){
  return key.replace(/_/g,"-")
}

//转换css value
function tranCssValue(v){
  if(typeof v == "string"){
    v = parseFloat(v.replace("/\%|px|em/g",""))
  }
  return v
}

//判断数组对象[{}] 的key 值是否存在
function checkObjValue(list,key,value){
  for(var i=0;i<list.length;i++){
    if(list[i][key] == value) return true;
  }
  return false;
}

//判断mac 是否合法
function checkMac(text){
  var pattern = /[0-9a-fA-F]{2}\:[0-9a-fA-F]{2}\:[0-9a-fA-F]{2}\:[0-9a-fA-F]{2}\:[0-9a-fA-F]{2}\:[0-9a-fA-F]{2}/
  return pattern.test(text)
}
//判断email是否合法
function checkEmail(text){
  var pattern = /^([a-zA-Z0-9]+[_|\_|\.]?)*[a-zA-Z0-9]+@([a-zA-Z0-9]+[_|\_|\.]?)*[a-zA-Z0-9]+\.[a-zA-Z]{2,3}$/,
    res = pattern.test(text)
  return res
}

//判断手机号码是否合法
function checkPhoneNum(text){
  var pattern = /[^0-9]/;
  if(pattern.test(text))
    return "手机号码只能是数字哟~"

  if(!text || text.split("").length != 11)
    return "手机号码必须是11位的数字哟~"

  return 0;
}

//获取对象的值
//list 为数组，key 为需要去除的key ， type 为最终获取的值的类型
function getObjValue(list,key,type){

  var result = [];
  for(var i =0;i<list.length;i++){
    //如果key 是数组，则返回多个对象【数组形式】
    if(typeof key != "string"){
      var obj = {};
      //取出每个key 列表的值，并且付给 obj[key]
      for(var j=0;j<key.length;j++){
        obj[key[j]] = list[i][key[j]];
      }
      result.push(obj);
    }else{
      var v = list[i][key]
      if(type == "int")
        v = parseInt(v);

      result.push(v)
    }
  }
  return result;
}

// 对象参数转url参数
export function paramsToUrl(params) {
  var res = '';
  try {
    let p = typeof params === 'string' ? JSON.parse(params) : params;
    for (let k in p) {
      if (res) {
        res += '&';
      }
      res += `${k}=${p[k]}`;
    }
  } catch (err) {
    res = params;
  }

  return res;
}

export {
  localSave,
  getDateTime,
  transCommDate,
  objFilter,
  checkMac,
  transChineseDate
}